package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.MeterCategory;
import com.hanserwei.community.entity.request.meter.MeterCategorySaveRequest;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.MeterCategoryMapper;
import com.hanserwei.community.service.MeterCategoryService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class MeterCategoryServiceImpl extends ServiceImpl<MeterCategoryMapper, MeterCategory> implements MeterCategoryService {

    @Override
    public boolean createCategory(MeterCategorySaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(!StringUtils.hasText(request.getName()), ResponseCodeEnum.INVALID_PARAMETER, "类型名称不能为空！");
        Long duplicate = lambdaQuery().eq(MeterCategory::getName, request.getName()).count();
        ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "类型名称已存在！");
        MeterCategory category = new MeterCategory();
        BeanUtils.copyProperties(request, category);
        boolean result = save(category);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateCategory(Integer id, MeterCategorySaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "类型ID参数错误！");
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        MeterCategory category = getById(id);
        ThrowUtils.throwIf(category == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "类型不存在！");
        if (StringUtils.hasText(request.getName()) && !request.getName().equals(category.getName())) {
            Long duplicate = lambdaQuery()
                    .eq(MeterCategory::getName, request.getName())
                    .ne(MeterCategory::getId, id)
                    .count();
            ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "类型名称已存在！");
        }
        BeanUtils.copyProperties(request, category);
        boolean result = updateById(category);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public List<MeterCategory> listAll() {
        return list();
    }
}
